package com.ethink.gateway.handler;

import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ethink.framework.common.constant.CommonConstant;
import com.ethink.framework.common.constant.CommonRespCode;
import com.ethink.framework.common.exception.BusinessException;
import com.ethink.gateway.constant.GatewayConstant;
import com.ethink.gateway.model.RequestEntityRule;
import com.ethink.gateway.properties.GateWayCommonProperties;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author name(Tel : mobile)
 * @Date 2020-06-11 10:03
 **/
@Slf4j
@Component
public class SystemRequestHandler extends RequestHandler {

    @Autowired
    private GateWayCommonProperties commonProperties;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource(name = "oauthHttpClient")
    private OkHttpClient oauthHttpClient;

    @Override
    public ServerHttpRequest handler(ServerHttpRequest httpServletRequest, RequestEntityRule requestEntityRule) {
        String tokenHeaderValue = httpServletRequest.getHeaders().getFirst(GatewayConstant.SYSTEM_USER_TOKEN_HEADER);
        if (StringUtils.isBlank(tokenHeaderValue)) {
            log.error("header中Authorization参数缺失");
            throw new BusinessException(CommonRespCode.NOT_LOGIN);
        }
        String accessToken = tokenHeaderValue.substring("Bearer".length()).trim();
        if (StringUtils.isBlank(tokenHeaderValue)) {
            log.error("header中Authorization参数解析失败, {}", tokenHeaderValue);
            throw new BusinessException(CommonRespCode.NOT_LOGIN);
        }
        UserInfo userInfo = getUserInfo(accessToken);
        if (userInfo == null) {
            log.error("获取用户信息失败, {}", accessToken);
            throw new BusinessException(CommonRespCode.NOT_LOGIN);
        }
        String loginName = userInfo.getLoginName();
        String realName = URLUtil.encode(userInfo.getName());
        if(StringUtils.isBlank(realName)) {
            realName = loginName;
        }
        // 封装增加的业务信息到请求头。
        httpServletRequest.mutate()
                .header(CommonConstant.RequestHeader.SYSTEM_LOGIN_NAME, loginName)
                .header(CommonConstant.RequestHeader.SYSTEM_REAL_NAME, realName)
                .build();
        log.info("current loginName: {}", loginName);
        return httpServletRequest;
    }

    private UserInfo getUserInfo(String accessToken) {
        Boolean persist = stringRedisTemplate.hasKey("auth:" + accessToken);
        if (persist == null || !persist) {
            log.error("redis中auth信息已失效, {}", accessToken);
            return null;
        }
        String principal = stringRedisTemplate.opsForValue().get("auth-principal:" + accessToken);
        if (StringUtils.isBlank(principal)) {
            log.error("redis中principal信息已失效, {}", accessToken);
            return null;
        }
        JSONObject root = JSON.parseObject(principal);
        return root.getObject("globalCustomerInfo", UserInfo.class);
    }

    @Data
    public static class UserInfo {
        /**
         * 全局用户id
         */
        private Long uid;
        /**
         * 登录用户名
         */
        private String loginName;
        /**
         * 姓名
         */
        private String name;
        /**
         * 手机号
         */
        private String mobile;

        /**
         * 工号
         */
        private String jobNumber;

        /**
         * 邮箱
         */
        private String email;
    }
}
